package com.example.myapp.Activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.example.myapp.ADO.MyViewPager;
import com.example.myapp.R;
import com.github.chrisbanes.photoview.PhotoView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;

public class ShowArryImg extends AppCompatActivity {
    private List<View> list = new ArrayList<>();
    private MyViewPager mVp;
    private Button downloadone;
    private Button downloadall;
    private String pathStr;
    private String index;    private int infoindex;
    private TextView tv_imgpage;
    private List<String> Listpath=new ArrayList<>();
    private String postcontent;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    downloadFile(Listpath.get(infoindex));
                break;
                case 1:
                    initList();

                    mVp.setAdapter(new VPAdapter());
                    mVp.setCurrentItem(infoindex);
                    tv_imgpage.setText((mVp.getCurrentItem()+1)+"/"+list.size());
                    break;
            }
        }
    };


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.show_image);

        tv_imgpage= findViewById(R.id.tv_imgpage);
        downloadone= findViewById(R.id.downloadone);
        ImageView showimgaeback= findViewById(R.id.showimgaeback);
        mVp = findViewById(R.id.mVp);
        Intent intent =getIntent();
        index=intent.getStringExtra("index");
        pathStr= intent.getStringExtra("pathArry");
        postcontent= intent.getStringExtra("postcontent");
        infoindex= Integer.valueOf(index);
        Listpath=  StrTolist(pathStr);
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);

        mVp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {
                //滑动时改变当前页码
                tv_imgpage.setText((i + 1)+"/"+list.size());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        downloadone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        });


        showimgaeback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    private void initList() {
        for (int i = 0; i < Listpath.size(); i++) {
            View v = View.inflate(ShowArryImg.this, R.layout.photoview_adapter, null);
            PhotoView photoView = v.findViewById(R.id.photo_view);
            Glide.with(getApplicationContext()).load(Listpath.get(i)).into(photoView);
            list.add(photoView);
        }
    }


    //    字符串转ArrayList<>()
    private List<String> StrTolist(String string){
        String newstr=string.substring(1,string.length()-1);
        String[] tokens = newstr.split(",");
        Log.w("aaab", "函数里:"+tokens[0]);
    List<String> b=new ArrayList<>();
      for (int i=0;i<tokens.length;i++){
          b.add(tokens[i].trim());
      }
        return b;
    }


    // 下载文件
    private void downloadFile(String url){
        int x=150000+(int)(Math.random()*5003);
        String imgname=x+".jpg";
//        Toast.makeText(ShowImage.this,imgname, Toast.LENGTH_SHORT).show();
        BmobFile file =new BmobFile(imgname,"",url);
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        File saveFile = new File(Environment.getExternalStorageDirectory(),"/PYB/"+ file.getFilename());
        file.download(saveFile, new DownloadFileListener() {
            @Override
            public void onStart() {
                Log.w("aaaa","开始下载...");
            }
            @Override
            public void done(String savePath, BmobException e) {
                if(e==null){
                    Log.w("aaaa","下载成功,保存路径:"+savePath);
                    Toast.makeText(ShowArryImg.this, "下载成功!\n保存路径:保存路径:/storage/emulated/0/PYB/", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(new File(savePath));
                    intent.setData(uri);
                    ShowArryImg.this.sendBroadcast(intent); // 发送广播通知相册
                }else{
                    Log.w("aaaa","下载失败："+e.getErrorCode()+","+e.getMessage());
                    Toast.makeText(ShowArryImg.this, "下载失败:\n请稍后再试..."+e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onProgress(Integer value, long newworkSpeed) {
                Log.i("bmob","下载进度："+value+","+newworkSpeed);
            }

        });
    }



//    自定义适配器
    public class VPAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {

            return view == object;
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int p = position % list.size();

            //获取当前的照片
            PhotoView img = (PhotoView) list.get(p);
            //获取照片的父容器
            ViewParent parent = img.getParent();
            //判断父容器不是空的话,删除的当前位置的照片,进行下一步操作，增加新的照片
            if (parent != null) {
                ViewGroup vp = (ViewGroup) parent;
                vp.removeView(list.get(p));

            }
            container.addView(list.get(p));


            return list.get(p);

        }




    @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
//      container.removeView(list.get(position%list.size()));
        }
    }


}
